package misc

import (
	"bytes"
	"regexp"
	"strconv"
	"strings"
)

var (
	keySpotVal      = regexp.MustCompile(`^.+: ?(.+)$`)
	keyEqualSignVal = regexp.MustCompile(`^.+ ?= ?(.+)$`)
)

// TwoSpotValue returns value from "key:value" or "key: value" line. The value will be not contains spaces
//
// Deprecated: use TwoSpotRexValue instead
func TwoSpotValue(line string) string {
	return strings.TrimSpace(strings.SplitN(line, ":", 2)[1])
}

// TwoSpotRexValue returns value from "key:value" or "key: value" line. The value will be not contains spaces
func TwoSpotRexValue(line string) string {
	res := keySpotVal.FindStringSubmatch(strings.TrimSpace(line))
	return res[len(res)-1]
}

// EqualSignRexValue returns value from "key=value" or "key = value" line. The value will be not contains spaces
func EqualSignRexValue(line string) string {
	res := keyEqualSignVal.FindStringSubmatch(strings.TrimSpace(line))
	return res[len(res)-1]
}

// RexSubStrSingleVal returns value in last position of out
func RexSubStrSingleVal(out []string) string {
	if len(out) != 2 {
		return ""
	} else {
		return out[1]
	}
}

// RemoveQuoteMark removes quote marks
func RemoveQuoteMark(line string) string {
	return strings.ReplaceAll(strings.ReplaceAll(line, "\"", ""), "'", "")
}

// IntExtractor returns int value from string represents of int
func IntExtractor(val string) int {
	if res, err := strconv.Atoi(val); err != nil {
		return -1
	} else {
		return res
	}
}

// RemoveBraces remove braces from line
func RemoveBraces(line string) string {
	line = strings.ReplaceAll(strings.ReplaceAll(line, "(", ""), ")", "")
	line = strings.ReplaceAll(strings.ReplaceAll(line, "{", ""), "}", "")
	line = strings.ReplaceAll(strings.ReplaceAll(line, "[", ""), "]", "")
	return line
}

func TrimOut(out []byte, err error) ([]byte, error) {
	out = bytes.TrimSpace(out)
	return out, err
}
